import requests
from loguru import logger
from retry import retry
import random
import nacos

#Nacos配置
NACOS_HOST="nacos.newacademic.net:8848"
NACOS_NAMESPACE_ID='d8f38fce-f5ee-4958-986f-6ecc3735db15'
NACOS_USER="nacos"
NACOS_PASS="qq123$%^"
SERVICE_NAME="public_service"
client = nacos.NacosClient(server_addresses=NACOS_HOST, namespace=NACOS_NAMESPACE_ID, username=NACOS_USER, password=NACOS_PASS, ak="nacos", sk="nacos")


def get_random_service_url(service_name):
    service_instance = client.list_naming_instance(service_name)

    if service_instance:
        random_number = random.randint(0, len(service_instance['hosts']) - 1)
        instance = service_instance['hosts'][random_number]
        host = instance["ip"]
        port = instance["port"]

        return f"http://{host}:{port}"
    else:
        return None

@retry(tries=2)
def CreateUrl(filepath,Type='local',day=3,title=''):
    '''
    基于相对路径生成绝对下载路径
    params:
        filepath: 相对路径
        Type: 类型 分为 local（本地），oss（ossdownload）,book(edown),dic(oss.dic.cool)
        day: 有效时间，默认3天
        title: 标题，如果有会带到下载地址里面，默认为空
    '''

    base_url = get_random_service_url(SERVICE_NAME)
    print(base_url)
    if not base_url:
        raise Exception("Nacos服务节点获取失败")
    url = f'{base_url}/GenerateDownloadAddress/'
    data = {
        'Type':Type,'path':filepath,'day':day,'title':title
    }
    response = requests.post(url,json=data,timeout=5)
    result = response.json()
    code = result['code']
    if code == 0:
        download_path = result['data']['download_path']
        return download_path
    else:
        logger.error(f'出现异常错误：{data["remark"]}')
        raise ValueError(data["remark"])


def get_scihub_url(doi_or_url):
    '''
    获取sci-hub下载地址
    '''
    base_url = get_random_service_url(SERVICE_NAME)
    if not base_url:
        raise Exception("Nacos服务节点获取失败")
    api_url = f'{base_url}/SciHubAddress/'
    data = {
        'url': doi_or_url
    }
    response = requests.post(api_url, json=data, timeout=5)
    result = response.json()
    code = result['code']
    if code == 0:
        download_path = result['data']['url']
        return download_path
    else:
        logger.error(f'出现异常错误：{data["remark"]}')
        raise ValueError(data["remark"])


def get_xaingsidu(image_link1,image_link2):
    url = f'http://192.168.45.129:8018/similarity/'
    data = {
        'image_link1': image_link1, 'image_link2': image_link2
    }
    response = requests.post(url, json=data, timeout=5)
    result = response.json()
    code = result['code']
    print(result)
    if code == 0:
        download_path = result['data']
        return download_path
    else:
        logger.error(f'出现异常错误：{result["remark"]}')
        raise ValueError(result["remark"])


if __name__ == '__main__':
    print(CreateUrl('/Applet/Email-Attachments/fm342897@163.com/2024-11-28/qy_Research and development progress of dynamic recrystallization in.pdf',Type='oss'))